const app = getApp()
// pages/device/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    device:{
      id:"q",
      name:"q"
    },
    services:[


    ],
    servicesCount:0,

    characters: [
      

    ],
    charactersCount: 0,
    curServiceUUID:"",
    curReadCharUUID:"",
    curReadContentHex:"",
    curReadContentChar:"",
    curWriteCharUUID:"",
    curWriteCharContent:"",
    curInputContent:""

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ device: app.globalData.connectedDevice});

    var _this=this;
    //获取设备service 列表
    wx.getBLEDeviceServices({
      deviceId: this.data.device.id,
      success: function(res) {
          _this.setData({services:res.services,servicesCount:res.services.length});
      },
      fail:function(res){
        console.log("get services fail");
      }
    });



  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
    //断开设备连接
    wx.closeBLEConnection({
      deviceId: this.data.device.id
    })

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  servicesItemTap:function(e){
    const ds = e.currentTarget.dataset;
    const serviceId = ds.id;

    //遍历修改service item状态
    this.data.services.forEach(function(service){
      console.log(service);
      if(service.uuid==serviceId){
        console.log("change");
        service.active=true;
      }else{
        console.log("change false");
        service.active = false;
      }
  
    });
    this.setData({services:this.data.services,curServiceUUID:serviceId});
    var _this=this;
    wx.getBLEDeviceCharacteristics({
      deviceId: this.data.device.id,
      serviceId: serviceId,
      success: function(res) {
          _this.setData({
            characters:res.characteristics,
            charactersCount:res.characteristics.length
          });
      },
      fail:function(res){
        console.log("characters get fail");
      }
    });


  },
  readBtnTap:function(e){
    const ds = e.currentTarget.dataset;
    const uuid=ds.id;

    this.setData({
      curReadCharUUID:uuid
    });

    var _this=this;
    wx.onBLECharacteristicValueChange(function(res){
      console.log(res);

  
      var content=_this.ab2hex(res.value);
      var chars=_this.buf2string(res.value);
      _this.setData({
        curReadContentHex:content,
        curReadContentChar:chars,
      });
    });

    //开始读取特征值
    wx.readBLECharacteristicValue({
      deviceId: this.data.device.id,
      serviceId: this.data.curServiceUUID,
      characteristicId: this.data.curReadCharUUID,
      success: function(res) {
        console.log("read char");
      },
    })


  },
  writeBtnTap:function(e){
    const ds = e.currentTarget.dataset;
    const uuid = ds.id;
    this.setData({
      curWriteCharUUID:uuid
    });

  },
  indicateBtnTap:function(e){
    const ds = e.currentTarget.dataset;
    const uuid = ds.id;

  },
  notifyBtnTap:function(e){
    const ds = e.currentTarget.dataset;
    const uuid = ds.id;
  }  
  ,ab2hex: (buffer) => {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join(' ');
  },
  buf2string: (buffer) => {
    var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
    var str = ''
    for (var i = 0; i < arr.length; i++) {
      str += String.fromCharCode(arr[i])
    }
    return str
  },

  bindKeyInput:function(e){
    this.setData({
      curInputContent:e.detail.value
    });
  },

  btnSendClick:function(){
    var content=this.data.curInputContent;
    var buffer=this.jointBuffer(content);
    wx.writeBLECharacteristicValue({
      deviceId: this.data.device.id,
      serviceId: this.data.curServiceUUID,
      characteristicId: this.data.curWriteCharUUID,
      value: buffer,
    });
    this.setData({
      curWriteCharContent:content
    });
  },
  jointBuffer: function (str) {

    let buffer = new ArrayBuffer(str.length);
    let dataView = new DataView(buffer);
    for (var i = 0; i < str.length; i++) {
      
      dataView.setUint8(i, str[i].charCodeAt(0));
    }


    return buffer;
  }


  
})